<template>
  <a-modal
    v-model:open="open"
    :afterClose="resetForm"
    :bodyStyle="bodyStyle"
    :confirmLoading="confirmLoading"
    :title="title"
    @ok="handleOk"
  >
    <a-spin :spinning="confirmLoading">
      <a-form
        ref="formRef"
        :labelCol="labelCol"
        :model="formState"
        :rules="rules"
        @keyup.enter.passive="handleOk"
      >
        <a-row :gutter="10">
          <a-col :span="24">
            <a-form-item
              label="项目名称"
              name="name"
            >
              <a-input
                v-model:value="formState.name"
                placeholder="请输入"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              label="国内访问地址"
              name="domesticUrl"
            >
              <a-input
                v-model:value="formState.domesticUrl"
                placeholder="请输入"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              label="国外访问地址"
              name="abroadUrl"
            >
              <a-input
                v-model:value="formState.abroadUrl"
                placeholder="请输入"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              :help="accountHelp"
              :validateStatus="accountValidateStatus"
              label="账号列表"
              required
              @blur.capture="resetAccountValidate"
            >
              <a-input-group
                v-for="(item, index) in formState.accountList"
                :key="index"
                class="account"
                compact
              >
                <a-input
                  v-model:value="item.username"
                  class="account-input"
                  placeholder="用户名"
                  allowClear
                >
                  <template #addonBefore>
                    <UserOutlined />
                  </template>
                </a-input>
                <a-input
                  v-model:value="item.password"
                  class="account-input"
                  placeholder="密码"
                  allowClear
                >
                  <template #addonBefore>
                    <LockOutlined />
                  </template>
                </a-input>
                <MinusCircleOutlined
                  v-if="formState.accountList.length > 1"
                  :disabled="formState.accountList.length === 1"
                  class="account-icon"
                  @click="removeAccount(index)"
                />
              </a-input-group>
              <a-button
                style="width: 100%"
                type="dashed"
                @click="addAccount"
              >
                <PlusOutlined />
                新增
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              label="对接指令系统"
              name="dockingSystem"
            >
              <a-select
                v-model:value="formState.dockingSystem"
                :options="dockingSystemOptions"
                mode="multiple"
                placeholder="请选择"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :span="16">
            <a-form-item
              label="时区"
              name="timeZone"
            >
              <a-input
                v-model:value="formState.timeZone"
                placeholder="请输入"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="排序"
              name="sort"
            >
              <a-input-number
                v-model:value="formState.sort"
                style="width: 100%"
                :min="0"
                :max="999"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script setup>
import { useBoolean } from '@/hooks/index.js'
import { message } from 'ant-design-vue'
import Service from '@/utils/service.js'
import { debounce } from 'lodash-es'

const title = ref('新增')
const [open, toggleOpen] = useBoolean()
const [confirmLoading, toggleConfirmLoading] = useBoolean()

const emit = defineEmits(['input'])

emit('input',1)

const labelCol = {
  span: 6,
}
const bodyStyle = {
  maxHeight: '400px',
  paddingRight: '10px',
  overflow: 'hidden auto',
}
const dockingSystemOptions = [
  {
    value: '2.0',
    label: '2.0',
  },
  {
    value: '3.0',
    label: '3.0',
  },
  {
    value: 'modbus',
    label: 'modbus',
  },
  {
    value: 'IC卡',
    label: 'IC卡',
  },
]

const form = {
  name: undefined,
  domesticUrl: undefined,
  abroadUrl: undefined,
  accountList: [{ username: '', password: '' }],
  dockingSystem: [],
  timeZone: undefined,
  sort: 0,
}
const formRef = ref()
let formState = reactive({ ...form })
const rules = {
  name: [
    {
      required: true,
      message: '请输入项目名称',
      trigger: 'blur',
    },
  ],
  domesticUrl: [
    {
      required: true,
      message: '请输入国内访问地址',
      trigger: 'blur',
    },
  ],
  abroadUrl: [
    {
      required: true,
      message: '请输入国外访问地址',
      trigger: 'blur',
    },
  ],
  dockingSystem: [
    {
      required: true,
      message: '请选择对接指令系统',
      trigger: 'change',
    },
  ],
  timeZone: [
    {
      required: true,
      message: '请输入时区',
      trigger: 'blur',
    },
  ],
}

const accountHelp = ref('')
const accountValidateStatus = ref('')
const [accountValidateFlag, toggleAccountValidateFlag] = useBoolean(true)

watch(
  () => formState.accountList,
  debounce(list => {
    const flag = list.every(item => item.username && item.password)
    toggleAccountValidateFlag(flag)
  }, 500),
  { deep: true }
)

const resetAccountValidate = () => {
  accountHelp.value = ''
  accountValidateStatus.value = ''
}

const addAccount = () => {
  formState.accountList.push({ username: '', password: '' })
}
const removeAccount = index => {
  formState.accountList.splice(index, 1)
}

const handleAdd = () => {
  title.value = '新增'
  toggleOpen(true)
}

const handleEdit = record => {
  title.value = '编辑'
  Object.assign(formState, record, {
    // accountList: JSON.parse(record.accountList),
    accountList: record.accountList ? [...record.accountList] : [],
    dockingSystem: record.dockingSystem.split(','),
  })
  toggleOpen(true)
}

const handleOk = () => {
  const validate1 = new Promise((resolve, reject) => {
    formRef.value
      .validate()
      .then(() => {
        resolve(true)
      })
      .catch(() => {
        reject(false)
      })
  })
  const validate2 = new Promise((resolve, reject) => {
    accountValidateStatus.value = 'validating'
    if (accountValidateFlag.value) {
      accountHelp.value = ''
      accountValidateStatus.value = 'success'
      resolve(true)
    } else {
      accountHelp.value = '请输入完整的用户名和密码'
      accountValidateStatus.value = 'error'
      reject(false)
    }
  })
  Promise.all([validate1, validate2]).then(([flag1, flag2]) => {
    if (flag1 && flag2) {
      const _dockingSystem = formState.dockingSystem.join(',')
      postFormState({
        ...toRaw(formState),
        dockingSystem: _dockingSystem,
      })
    }
  })
}

const resetForm = () => {
  formState = reactive({ ...form })
  resetAccountValidate()
  formRef.value.resetFields()
}

const emit = defineEmits(['modalOk'])
const postFormState = async form => {
  const isEdit = !!form.id
  toggleConfirmLoading()
  const { code, msg } = await Service.postAction('/website/saveOrUpdate', form)
  toggleConfirmLoading()
  if (code === 200) {
    toggleOpen(false)
    message.success(`${isEdit ? '编辑' : '新增'}成功！`)
    emit('modalOk')
  } else {
    message.error(msg)
  }
}

defineExpose({ handleAdd, handleEdit })
</script>

<style lang="scss" scoped>
.account {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  &-input {
    width: calc(50% - 10px);
  }

  &-icon {
    color: #999;
    margin-left: 10px;

    &:hover {
      color: #777;
    }
  }
}
</style>
